package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;

import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    private static final String CURRENT_USER = "CURRENT_USER";
    @Reference
    private UserService userService;

    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}",param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        //用户不存在或密码不匹配则登录失败
        if (null == user || !user.getPassword().equals(param.getPassword())) {
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        //用户信息写入 session
        request.getSession(true).setAttribute(CURRENT_USER, user);
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    /**
     * 登出
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/logout")
    public Result logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        log.info("[登出]……");
        //从session中删除用户
        request.getSession().removeAttribute(CURRENT_USER);
        //重定向到登录页
        response.sendRedirect("http://oms.health.itcast.com:8080/pages/login.html");
        return null;
    }


    /**
     * 获取当前登录用户名
     *
     * @return
     */
    @RequestMapping("/getUsername")
    public Result getUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null != principal && principal instanceof org.springframework.security.core.userdetails.User) {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) principal;
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }

    @RequestMapping("/loginSuccess")
    public Result loginSuccess() {
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    @RequestMapping("/loginFail")
    public Result loginFail() {
        return new Result(false, "登录失败");
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user, Integer[] RoleIds){
        log.info("[用户新增]data:{},{}",user,RoleIds);
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userService.add(user, RoleIds);
        return new Result(true,MessageConst.ADD_USER_SUCCESS);
    }

    @PostMapping("/delete")
    public Result delete(Integer id) {
        userService.deleteById(id);
        return new Result(true, MessageConst.DELETE_USER_SUCCESS);
    }

    /**
     * 查询所有
     * @return
     */
    @RequestMapping("findAll")
    public Result findAll() {
        log.info("[用户-查询所有]");
        List<Role> role = userService.findAll();
        return new Result(true,MessageConst.QUERY_USER_SUCCESS,role);
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @GetMapping("findPage")
    public Result findPage(QueryPageBean queryPageBean) {
        log.info("[用户-分页查询]data:{}", queryPageBean);
        //rpc查询数据
        PageResult pageResult = userService.pageQuery(queryPageBean);
        //封装返回结果
        ArrayList<User> users = new ArrayList<>();
        for (Object o : pageResult.getRows()) {
            User user = (User) o;
            Set<Role> roles = user.getRoles();
            StringBuilder name = new StringBuilder();
            for (Role role : roles) {
                name.append(role.getName());
                name.append(",");
            }
            user.setRoless(name.toString());
            users.add(user);
        }
        Long total = pageResult.getTotal();
        PageResult pageResult1 = new PageResult();
        pageResult1.setRows(users);
        pageResult1.setTotal(total);
        log.debug("acccc:{}",pageResult1);
        return new Result(true,MessageConst.ACTION_SUCCESS, pageResult1);
    }

    /**
     * 根据id查找用户
     * @param id
     * @return
     */
    @GetMapping("findById")
    public Result findById(Integer id) {
        User user = userService.findById(id);
        return new Result(true, MessageConst.ACTION_SUCCESS,user);
    }

    /**
     * 根据id查找用户对应角色
     * @param userId
     * @return
     */
    @GetMapping("findRolesById")
    public Result findRolesById(Integer userId) {
        List<Integer> roleIds = userService.findRolesById(userId);
        return new Result(true, MessageConst.ACTION_SUCCESS, roleIds);
    }

    /**
     * 更新用户
     * @param user
     * @param RoleIds
     * @return
     */
    @PostMapping("update")
    public Result update(@RequestBody User user, Integer[] RoleIds) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userService.update(user, RoleIds);
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }
}
